<?php
namespace Modules\Activity\Entities\Jika;;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;

use Modules\Order\Traits\Skuable;
use \Modules\Chip\Entities\Chip;

// 一番赏活动 副表
class Task extends Model
{
    use Skuable;
    
    protected $table = 'jika_tasks';

   	protected $guarded = [];
    static public $resourcename = '集卡任务';

    protected $casts = [
        'chip_ids' => 'json',
        'link' => 'json'
    ];

    public function activity()
    {
        return $this->belongsTo('\Modules\Activity\Entities\Jika\Activity', 'activity_id');
    }

    // 所有sku
    public function skus()
    {
        return $this->hasMany('\Modules\Activity\Entities\Jika\Sku', 'task_id')->orderBy('list_weight', 'desc')->orderBy('id', 'asc');
    }

    // 兑换记录
    public function swap_records()
    {
        return $this->hasMany('\Modules\Activity\Entities\Jika\SwapRecord', 'task_id');
    }

    // 获取此任务所需碎片
    public function getChipList($user = NULL)
    {
        $chips = Chip::ids($this->chip_ids)->get();

        if ($user) {
            $chips->each(function ($chip) use ($user) {
                $chip->user_stock = $user->getChipAssetBalance($chip->id);
            });
        }

        return $chips;
    }

    // 检查是否超出兑换次数限制
    public function checkSwapLimit($user)
    {
        if ($this->swap_limit) {
            $sum = $this->swap_records()->where('user_id', $user->id)->count();

            if ($sum >= $this->swap_limit) {
                return false;
            }
        }

        return true;
    }
}
